<?php
/**
 * User: b179a9
 * Date: 9/30/11
 * Time: 6:49 PM
 */

namespace Managers;

class Tags extends BaseManager implements MatchesManager
{

    protected $__table = self::TABLE;
    const TABLE = '\Catalog\Tags';

    protected function createQueryBuilder()
    {
        $qb = $this->_em->createQueryBuilder()
            ->select('t, partial n.{id, title}')
            ->from($this->__table, 't')
            ->join('t.news', 'n')
            ->andWhere('t.isDel = 0');
        return $qb;
    }

    public function getByMatches(array $matches)
    {
        $matchesIds = Utils::rebuildArray($matches);
        $qb = $this->createQueryBuilder();
        $qb->andWhere($qb->expr()->in('t.id', $matchesIds));
        $res = $qb->getQuery()->getArrayResult();
        return $res;
    }

    public function createByWords(array $words)
    {
        $entities = array();
        foreach ($words as $word) {
            $entity = $this->_em->getRepository($this->__table)->findOneByName($word);
            if (!$entity) {
                $entity = new \Catalog\Tags();
                $entity->setIsDel(false);
                $entity->setName($word);
                $this->_em->persist($entity);
            }
            $entities[] = $entity;
        }
        $this->flush();
        return $entities;
    }

    public function getByIdWithNews($id)
    {
        $res = $this->getById($id);
        if ($res) {
            $newsManager = new News();
            $res['news'] = $newsManager->getByMatches($res['news']);
        }
        return $res;
    }

    public function getById($id)
    {
        $qb = $this->createQueryBuilder()
            ->andWhere('t.id = :id')->setParameter('id', $id);
        $res = $qb->getQuery()->getArrayResult();
        return count($res) ? $res[0] : false;
    }
}
